package com.atming.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

@Slf4j
@Component
public class AccessFilter extends ZuulFilter {


    //过滤类型
    @Override
    public String filterType() {
        return "pre";
    }

    //执行顺序  小 高
    @Override
    public int filterOrder() {
        return 1;
    }

    // 执行条件 true开启
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //动作  具体逻辑
    @Override
    public Object run() throws ZuulException {

        //模拟异常
        //Integer.parseInt("dfsad的撒旦");

        //获取上下文
        RequestContext rc=RequestContext.getCurrentContext();
        HttpServletRequest request = rc.getRequest();
        //获取表单的token
        String token = request.getParameter("token");


        //业务逻辑处理
        if(null==token){
            log.warn("token is  null ...");
            //请求结束不往下处理
            rc.setSendZuulResponse(false);
            //相应状态码，HTTP 401 错误代表用户没有权限
            rc.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            //响应类型
            rc.getResponse().setContentType("application/json; charset=utf-8");
            PrintWriter writer=null;
            try{
                writer = rc.getResponse().getWriter();
                writer.println("{\"message\":\""+HttpStatus.UNAUTHORIZED.getReasonPhrase()+"\"}");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(null!=writer){
                    writer.close();
                }
            }

        }else{
            log.info("token is  ok！ ...");
        }

        return null;
    }
}
